import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/index.js'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/index.vue') // 登录页 | 注册页
    },
    {
      path: '/home',
      component: () => import('@/views/home/index.vue'), // 首页
      children: [
        {
          path: '/channel',
          component: () => import('@/views/home/second/ArticleType.vue') // 文章分类
        },
        {
          path: '/manager',
          component: () => import('@/views/home/second/ArticleManager.vue') // 文章管理
        },
        {
          path: '/user/profile',
          component: () => import('@/views/home/second/UserInfo.vue') //基本资料
        },
        {
          path: '/user/avatar',
          component: () => import('@/views/home/second/ChangeAvatar.vue') //更换头像
        },
        {
          path: '/user/password',
          component: () => import('@/views/home/second/ResetPassword.vue') // 重置密码
        }
      ]
    },
    {
      path: '/',
      redirect: '/manager'
    }
  ]
})

// 前置路由守卫 跳转路由需携带token
// 因为请求后端接口时必须携带token请求头 若不携带会返回 401状态码
// 而401状态码会被 axios响应拦截器拦截 提示登录超时 跳转登录页
router.beforeEach(async (to) => {
  const userStore = useUserStore()
  // 如果访问的不是登录页 且 没有携带token 重定向到登录页
  if (to.path !== '/login' && !userStore.token) {
    ElMessage({
      message: '登录已过期',
      type: 'error',
      plain: true
    })
    return '/login'
  }

  // 返回undfind 即放行
})

export default router
